package com.stylefeng.guns.core.util.excels.file.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.google.common.base.Strings;
import com.stylefeng.guns.core.util.excels.config.ReturnConfig;
import com.stylefeng.guns.core.util.excels.config.ReturnPropertyParam;
import com.stylefeng.guns.core.util.excels.file.ExcelToModel;
import com.stylefeng.guns.modular.pay.exception.BusinessExcption;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;


/**
 * @author horsery
 * @filename ExcelToModelImpl.java
 * @createTime 2008-4-10 上午11:21:40
 * @version 类说明
 */
public class ExcelToModelImpl implements ExcelToModel {
	private InputStream inputStream;
	private ReturnConfig excelConfig;
	private int sheetRow;
	private Logger log = Logger.getLogger(this.getClass());

	public ExcelToModelImpl(InputStream inputStream, ReturnConfig excelConfig) {
		this.inputStream = inputStream;
		this.excelConfig = excelConfig;
	}
	@Override
	public Integer getSheetRow() {
		// TODO Auto-generated method stub
		return sheetRow;
	}
	
	public List getModeList(int sheetn) throws Exception {
		// TODO Auto-generated method stub
		List modeList = new ArrayList();
		Workbook book;
		try {
			book = Workbook.getWorkbook(inputStream);
			Sheet sheet = book.getSheet(sheetn);
			this.sheetRow = sheet.getColumns();
			for (int i = 1; i < sheet.getRows(); i++) {
				Object obj = this.getModelClass(excelConfig.getClassName());
				BeanWrapper bw = new BeanWrapperImpl(obj);
				String check = sheet.getCell(0, i).getContents();
				System.out.println("no："+i+"  check: "+check);
				if(check==null||"".equals(check)||(check.length()>=2&&"备注".equals(check.substring(0, 2)))){
					break;
				}
				for (int j = 0; j < sheet.getColumns(); j++) {
					// 取得Excel表头
					String excelTitleName = sheet.getCell(j, 0).getContents().trim();
//					System.out.println("excelTitleName："+excelTitleName);
					// 取得Excel值
					String value = sheet.getCell(j, i).getContents().trim();
//					System.out.println(value);
//					if("".equals(value.trim())||value==null)
//						continue;
					// 取得配置属性	
					ReturnPropertyParam propertyBean = (ReturnPropertyParam) excelConfig.getPropertyMap().get(excelTitleName);
					if (propertyBean != null) {
						//非空校验
//						System.out.println(propertyBean.getRequire());
//						if("true".equalsIgnoreCase(propertyBean.getRequire()) && Strings.isNullOrEmpty(value)){
//							throw new BusinessExcption("【"+excelTitleName+"】字段不能为空");
//						}
//						String length = propertyBean.getMaxLength();
////						System.out.println(length);
//						if(!Strings.isNullOrEmpty(value) && value.length()>Integer.parseInt(length)){
//							throw new BusinessExcption("【"+excelTitleName+"】字段超出长度");
//						}
                        if("Date".equalsIgnoreCase(propertyBean.getDataType())){
                        	try {
                        		if(value.contains("/")){
                        			value = value.replace("/", "-");
                        		}
                        		System.out.println("propertyBean.getDateFormat()------"+propertyBean.getDateFormat());
                        		SimpleDateFormat sdf = new SimpleDateFormat(propertyBean.getDateFormat());
								Date tempDate = sdf.parse(value);
								bw.setPropertyValue(propertyBean.getName(), tempDate);
								continue;
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								log.error("日期转换失败");
								continue;
							}
                        }
                        if("BLOB".equalsIgnoreCase(propertyBean.getDataType())){
                        	byte[] tempBytes = value.getBytes();
							bw.setPropertyValue(propertyBean.getName(), tempBytes);
							continue;
                        }
						bw.setPropertyValue(propertyBean.getName(), value);
					}
				}
				modeList.add(obj);
			}
			book.close();
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return modeList;
	}

	private Object getModelClass(String className) {
		Object obj = null;
		try {
			obj = Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}


}
